/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.web.misc.license;

import java.math.BigInteger;

public abstract class GroupUtil {

    public static String encodeGroups(BigInteger plain) {
        BigInteger max = BigInteger.valueOf(60466176L);
        StringBuffer buff = new StringBuffer();
        int i = 0;
        while (plain.compareTo(BigInteger.ZERO) != 0) {
            int j = plain.mod(max).intValue();
            String encoded = encodeGroup(j);
            if (i > 0) {
                buff.append("-");
            }
            buff.append(encoded);
            plain = plain.divide(max);
            i++;
        }
        return buff.toString();
    }

    public static String encodeGroup(int value) {
        StringBuffer buff = new StringBuffer();
        int i = 36;
        for (int j = 0; j < 5; j++) {
            int k = value % i;
            char c = (char) (k < 10 ? (48 + k) : (65 + k - 10));
            buff.append(c);
            value /= i;
        }
        return buff.toString();
    }

    public static BigInteger decodeGroups(String encoded) throws InvalidLicenseException {
        BigInteger orig = BigInteger.ZERO;
        BigInteger max = BigInteger.valueOf(60466176L);
        int i = encoded.length();
        while (i >= 0) {
            int j = encoded.lastIndexOf('-', i - 1) + 1;

            String str = encoded.substring(j, i);
            int k = decodeGroup(str);
            orig = orig.multiply(max);
            orig = orig.add(BigInteger.valueOf(k));

            i = j - 1;
        }
        return orig;
    }

    public static int decodeGroup(String paramString) throws InvalidLicenseException {
        if (paramString.length() != 5) {
            throw new InvalidLicenseException();
        }

        int i = 36;
        int j = 0;
        for (int k = paramString.length() - 1; k >= 0; k--) {
            int m = paramString.charAt(k);
            int n;
            if ((48 <= m) && (m <= 57)) {
                n = m - 48;
            } else if ((65 <= m) && (m <= 90)) {
                n = m - 65 + 10;
            } else {
                throw new InvalidLicenseException();
            }

            j *= 36;
            j += n;
        }

        return j;
    }

    protected GroupUtil() {
    }
}